package server

import (
	"encoding/json"
	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"time"
	myjwt "xinyuan/TexasHoldem/jwt"
)

var dealer Dealer

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

var j *myjwt.JWT //jwt 生成验证

func init() {
	dealer = Dealer{
		Player:    make([]*Player, 0, 9),
		PlayerMap: make(map[string]*Player),
		Button:    0,
		index:     1,
		LastBet:   10,
	}
	j = &myjwt.JWT{
		SigningKey: []byte("texas"),
	}
	log.Println("api init")
}

//webSocket 请求 ping 返回 pong
func Ping(c *gin.Context) {
	// 升级 get 请求为 webSocket 协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer ws.Close()
	log.Println("connct")
	for {
		// 读取 ws 中的数据
		mt, message, err := ws.ReadMessage()
		if err != nil {
			break
		}
		if string(message) == "ping" {
			message = []byte("pong")
		}
		// 写入 ws 数据
		err = ws.WriteMessage(mt, message)
		if err != nil {
			break
		}
	}

	log.Println("disConnect")
}

func Desk(c *gin.Context) {
	user := c.PostForm("user")
	if "" == user {
		c.Redirect(http.StatusMovedPermanently, "http://localhost:8080/login")
	} else {
		//用户是否存在
		if _, ok := dealer.PlayerMap[user]; ok {
			c.Redirect(http.StatusMovedPermanently, "http://localhost:8080/login")
			return
		}
		t, e := generateToken(user)
		if e != nil {
			log.Println("create token error", e)
			c.Redirect(http.StatusMovedPermanently, "http://localhost:8080/login")
		} else {
			c.HTML(http.StatusOK, "desk.html", gin.H{
				"title": "hall",
				"token": t,
				"user":  user,
			})
		}
	}
}

// 生成令牌
func generateToken(user string) (token string, err error) {
	claims := myjwt.CustomClaims{
		Name: user,
		StandardClaims: jwtgo.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 10000), // 签名生效时间
			ExpiresAt: int64(time.Now().Unix() + 36000), // 过期时间 一小时
			Issuer:    "pp",                             //签名的发行者
		},
	}

	token, err = j.CreateToken(claims)
	log.Println(token)
	return
}

func Socket(c *gin.Context) {
	// 升级 get 请求为 webSocket 协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer ws.Close()
	log.Println("socket Connect")
	var player = &Player{}

	for {
		// 读取 ws 中的数据
		_, message, err := ws.ReadMessage()
		if err != nil {
			log.Println("readMessage err:", err)
			break
		}

		lreq := Reqeust{}
		json.Unmarshal(message, &lreq)

		switch lreq.Type {
		case "connect":
			if claim, e := j.ParseToken(lreq.People.Token); e == nil {
				log.Println(claim.Name, "connect success")
				player.Name = claim.Name
				player.Token = lreq.People.Token
				player.Conn = ws
				player.Total = 2000
				player.Bet = [4]int{-1, -1, -1, -1}
				dealer.AddPlayer(player)
			} else {
				log.Println("create jwt token error")
				break
			}
		case "ready":
			dealer.ReadyPlayer(player)
		case "bet":
			dealer.PlayerAction(player, lreq.Bet.Value)
		}

	}

	//用户下线
	dealer.RemovePlayer(player)

	log.Println("socket disConnect")
}
